package cn.v2tila.rsosa.management.service.serviceImpl;

import cn.v2tila.rsosa.management.entity.MgtUserEntity;
import cn.v2tila.rsosa.management.jpa.MgtUserJPA;
import cn.v2tila.rsosa.management.service.MgtUserService;
import cn.v2tila.rsosa.management.utils.PageDataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author v2tila on 16:03 2019/2/7
 */
@Service
public class MgtUserServiceImpl implements MgtUserService {

    @Autowired
    private MgtUserJPA mgtUserJPA;

    public PageDataResult getMgtUsers(int page, int limit, MgtUserEntity mgtUserEntity) {

        PageDataResult pageDataResult = new PageDataResult();
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        ExampleMatcher matcher;

        if(mgtUserEntity.getId()==0){
            matcher = ExampleMatcher.matching()
                    .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withIgnorePaths("id");
        }else{
            matcher = ExampleMatcher.matching();
        }
        Example<MgtUserEntity> example = Example.of(mgtUserEntity,matcher);
        Page<MgtUserEntity> pages = mgtUserJPA.findAll(example,pageable);
        List<MgtUserEntity> userEntityList = pages.getContent();
        int count = pages.getTotalPages();
        pageDataResult.setData(userEntityList);
        pageDataResult.setCount(count);
        return pageDataResult;


    }

    public List<MgtUserEntity> findAll() {
        return mgtUserJPA.findAll();
    }

    @Override
    public MgtUserEntity findByUsername(String username) {
        return mgtUserJPA.findByUsername(username);
    }

}
